<template>
  <div class="innerBox">
    <p :style="{ textAlign: 'right', marginBottom: '5px' }">
      <a-button type="primary" link @click="action('add')"
        ><template #icon>
          <PlusOutlined />
        </template>
        添加</a-button
      >
       <a-button type="link" @click="downloadTemplate">
          <template #icon>
            <download-outlined />
          </template>
          下载模板
        </a-button>
        <a-upload
          :showUploadList="false"
          accept=".xls,.xlsx"
          :customRequest="
            ({ file }) => {
              uploadExcel(file);
            }
          "
          :disabled="disabled"
        >
          <a-button type="link" :disabled="disabled">
            <upload-outlined></upload-outlined>
            上传
          </a-button>
        </a-upload>
    </p>
    <a-table
      :data-source="state.data"
      :columns="state.columns"
      stripe
      bordered
      :pagination="state.pager"
      size="small"
      :scroll="{ x: 1200 }"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <a-space :size="10" spacer="|">
            <DeleteBtn
              title="确认删除?"
              label="删除"
              @onDelete="action('remove', record)"
            />
            <a-button type="link" @click="action('edit', record)" link
              ><template #icon>
                <EditOutlined />
              </template>
              编辑</a-button
            >
          </a-space>
        </template>
        <template v-if="column.key === 'dept'"
          >{{ showDept(record.departId) }}
        </template>
      </template>
    </a-table>
    <FormModal
      :formConfig="state.formConfig"
      @submit="submit"
      ref="dialogRef"
    />
  </div>
</template>

<script setup>
import { getCurrentInstance, reactive, ref, watch, onBeforeMount } from "vue";
import _ from "lodash";
import FormModal from "@/components/FormModal.vue";
import DeleteBtn from "@/components/DeleteBtn.vue";

const { proxy } = getCurrentInstance();

const props = defineProps(["type", "orderId"]);

const columns = {
  // 使用材料
  0: [
    {
      title: "所属部门",
      dataIndex: "dept",
      key: "dept",
      width: 100,
      ellipsis: true,
    },
    {
      title: "供货单位",
      dataIndex: "supplierUnit",
      key: "supplierUnit",
      width: 100,
      ellipsis: true,
    },
    {
      title: "领料部门",
      dataIndex: "pickingDepart",
      width: 100,
      ellipsis: true,
      key: "pickingDepart",
    },
    {
      title: "事务类型",
      dataIndex: "transactionType",
      width: 100,
      ellipsis: true,
      key: "transactionType",
    },
    {
      title: "领用项目编号",
      dataIndex: "projectCode",
      width: 100,
      ellipsis: true,
      key: "projectCode",
    },
    {
      title: "领用项目名称",
      dataIndex: "projectName",
      width: 100,
      ellipsis: true,
      key: "projectName",
    },
    {
      title: "物料编码",
      dataIndex: "materialCode",
      width: 80,
      ellipsis: true,
      key: "materialCode",
    },
    {
      title: "物料名称",
      dataIndex: "materialName",
      width: 100,
      ellipsis: true,
      key: "materialName",
    },
    {
      title: "物料组",
      dataIndex: "materialGroup",
      width: 80,
      ellipsis: true,
      key: "materialGroup",
    },
    {
      title: "发货数量",
      dataIndex: "shippedNum",
      width: 80,
      ellipsis: true,
      key: "shippedNum",
    },
    {
      title: "业务单位",
      dataIndex: "unit",
      width: 80,
      ellipsis: true,
      key: "unit",
    },
    {
      title: "单根重量(KG)",
      dataIndex: "unitWeight",
      width: 80,
      ellipsis: true,
      key: "unitWeight",
    },
    {
      title: "总重量(KG)/容量(L/桶)",
      dataIndex: "totalWeight",
      key: "totalWeight",
      width: 80,
      ellipsis: true,
    },
    {
      title: "采购单位",
      dataIndex: "buyingCom",
      width: 80,
      ellipsis: true,
      key: "buyingCom",
    },
    {
      title: "供应商",
      dataIndex: "supplierCom",
      width: 100,
      ellipsis: true,
      key: "supplierCom",
    },
    {
      title: "操作",
      dataIndex: "action",
      key: "action",
      fixed: "right",
      width: 180,
      align: "center",
    },
  ],
  // 使用设备
  1: [
    {
      title: "所属部门",
      dataIndex: "dept",
      key: "dept",
    },
    { title: "供货单位", dataIndex: "supplierUnit", key: "supplierUnit" },
    { title: "使用设备", dataIndex: "machine", key: "machine" },
    { title: "设备型号", dataIndex: "machineCode", key: "machineCode" },
    { title: "数量", dataIndex: "num", key: "num" },
    { title: "单位", dataIndex: "unit", key: "unit" },
    { title: "使用时长", dataIndex: "hours", key: "hours" },
    {
      title: "操作",
      dataIndex: "action",
      key: "action",
      width: 180,
      align: "center",
    },
  ],
};
const formItems = {
  // 使用材料
  0: [
    {
      type: "hidden",
      name: "id",
    },
    {
      label: "部门",
      type: "select",
      name: "departId",
      options: [],
      span: 12,
      rules: [
        {
          required: true,
          message: "必填",
        },
      ],
    },
    {
      label: "供货单位",
      type: "input",
      name: "supplierUnit",
      span: 12,
    },
    { label: "领料部门", type: "input", name: "pickingDepart", span: 12 },
    { label: "事务类型", type: "input", name: "transactionType", span: 12 },
    { label: "领用项目编号", type: "input", name: "projectCode", span: 12 },
    { label: "领用项目名称", type: "input", name: "projectName", span: 12 },
    { label: "物料编码", type: "input", name: "materialCode", span: 12 },
    { label: "物料名称", type: "input", name: "materialName", span: 12 },
    { label: "物料组", type: "input", name: "materialGroup", span: 12 },
    {
      label: "发货数量",
      type: "number",
      name: "shippedNum",
      span: 12,
    },
    { label: "业务单位", type: "input", name: "unit", span: 12 },
    {
      label: "单根重量(KG)",
      type: "number",
      name: "unitWeight",
      span: 12,
    },
    {
      label: "总重量(KG)/容量(L/桶)",
      type: "number",
      name: "totalWeight",
      span: 12,
    },
    { label: "采购单位", type: "input", name: "buyingCom", span: 12 },
    { label: "供应商", type: "input", name: "supplierCom", span: 12 },
  ],
  // 使用设备
  1: [
    {
      type: "hidden",
      name: "id",
    },
    {
      label: "部门",
      type: "select",
      name: "departId",
      options: [],
      span: 12,
      rules: [
        {
          required: true,
          message: "必填",
        },
      ],
    },
    { label: "供货单位", type: "input", name: "supplierUnit", span: 12 },
    { label: "使用设备", type: "input", name: "machine", span: 12 },
    { label: "设备型号", type: "input", name: "machineCode", span: 12 },
    {
      label: "数量",
      type: "number",
      name: "num",
      span: 12,
      rules: [
        {
          required: true,
          message: "必填",
        },
      ],
    },
    { label: "单位", type: "input", name: "unit", span: 12 },
    {
      label: "使用时长",
      type: "num",
      name: "hours",
      span: 12,
      rules: [
        {
          required: true,
          message: "必填",
        },
      ],
    },
  ],
};
const apis = {
  0: "/material/solid",
  1: "/material/machine",
};


const downloadTemplate = () => {
  console.log('props.type',props.type)
  let type = props.type===0?1:2
  // 后端接口地址（相对路径）
  const url = `http://localhost:8082/api/excel/import/material?type=${type}`;

  // 创建临时 a 标签
  const link = document.createElement("a");
  link.href = url; // 直接使用相对路径，由 axios baseURL 或 Nginx 处理
  link.download = "能源数据导入模板.xlsx"; // 指定下载的文件名
  link.style.display = "none";

  // 添加到 DOM 并触发点击
  document.body.appendChild(link);
  link.click();

  // 移除元素
  document.body.removeChild(link);
};


const uploadExcel = async (file) => {
  // 1. 文件校验（可选）
  const isExcel =
    file.type === "application/vnd.ms-excel" ||
    file.type ===
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

  if (!isExcel) {
    proxy.$message.error("只能上传 Excel 文件（.xls 或 .xlsx）!");
    return false;
  }

  // 限制文件大小（例如 10MB）
  const maxSize = 10 * 1024 * 1024; // 10MB
  if (file.size > maxSize) {
    proxy.$message.error("文件大小不能超过 10MB！");
    return false;
  }

  // 2. 构建 FormData
  const formData = new FormData();
  formData.append("file", file);
  formData.append("shipRepairId", props.orderId); 


  let uploadUrl;
  if (props.type === 0) {
    uploadUrl = "/excel/import/solid";   // 使用材料
  } else if (props.type === 1) {
    uploadUrl = "/excel/import/machine"; // 使用设备
  } else {
    proxy.$message.error("未知的类型，无法确定上传接口！");
    return false;
  }

    // 3. 调用上传接口
    const { success, msg, data } = await proxy.$axios.post(
      uploadUrl, // 后端上传接口路径
      formData,
      {
        headers: {
          "Content-Type": "multipart/form-data",
        },
        // 可选：显示上传进度
        onUploadProgress: (progressEvent) => {
          const percentCompleted = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          );
          console.log(`上传进度: ${percentCompleted}%`);
          // 可结合 a-upload 的 fileItem.status 实现进度条
        },
      }
    );

    // 4. 处理响应
    if (success) {
      proxy.$message.success("文件上传成功！");
      // 上传成功后刷新数据
      //search({ factory: state.factory, type: state.type, year: state.year });
      getData(1)
    } else {
      proxy.$message.error(msg || "上传失败，请检查文件内容");
    }

};


const state = reactive({
  depts: [],
  columns: [],
  data: [],
  formConfig: {},
  pager: {
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: false,
    size: "normal",
  },
});
const dialogRef = ref();

onBeforeMount(() => {
  // 获取所有的部门
  proxy.$axios.get("/department/list").then(({ success, data }) => {
    if (success) {
      state.depts = data;

      const opts = _.map(data, (o) => ({ label: o.name, value: o.id }));
      const departId_0 = _.find(formItems[0], { name: "departId" });
      departId_0.options = opts;
      const departId_1 = _.find(formItems[1], { name: "departId" });
      departId_1.options = opts;
    }
  });
});

let api = null;
let getData = null;
watch(
  [() => props.type, () => props.orderId],
  ([type, orderId]) => {
    let title;
    if (type === 0) {
      title = "使用材料";
    } else if (type === 1) {
      title = "使用设备";
    }
    state.formConfig = {
      title: `${title}提交`,
      items: formItems[type],
    };
    state.columns = columns[type];

    if (orderId) {
      api = apis[type];
      // 获取数据函数
      getData = async (page) => {
        const { success, data } = await proxy.$axios.get(`${api}/list`, {
          params: {
            pageNumber: page,
            pageSize: state.pager.pageSize,
            shipRepairId: orderId,
          },
        });
        if (success) {
          const { content, totalElements } = data;
          state.data = content;
          state.pager.total = totalElements;
          state.pager.current = page;
        }
      };

      getData(1);
    }
  },
  { immediate: true }
);

const handleTableChange = ({ current }) => {
  getData(current);
};

const submit = (values) => {
  let method = "post";
  let url = api;
  if (values.id) {
    method = "put";
    url += `/${values.id}`;
  }
  values.shipRepairId = props.orderId;
  proxy.$axios({ method, data: values, url }).then(({ success, msg }) => {
    if (success) {
      dialogRef.value.cancel();
      proxy.$message.success("提交成功");
      getData(1);
    }
  });
};

const action = (type, record) => {
  if (type === "add") {
    dialogRef.value.handleOpenForm({});
  } else if (type === "edit") {
    dialogRef.value.handleOpenForm({ ...record });
  } else if (type === "remove") {
    proxy.$axios.delete(`${api}/${record.id}`).then(({ success }) => {
      if (success) {
        getData(1);
      }
    });
  }
};

const showDept = (deptId) => {
  const dept = _.find(state.depts, { id: deptId });
  return dept?.name;
};
</script>

<style lang="less" scoped>
.innerBox {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  overflow-y: auto;
}
</style>
